package dao

import (
	"gitee.com/tietang/terrace-go/v2/lib/rpc"
	"gitee.com/tietang/terrace-go/v2/lib/rpc/mo/entity"
	"gitee.com/tietang/terrace-go/v2/lib/rpc/models"
	"gitee.com/tietang/terrace-go/v2/lib/rpc/seri"
	log "github.com/sirupsen/logrus"
	"reflect"
)

type Dao interface {
	Init()
	Save(metrics any)
}

var _ Handler = new(DaoHandler)
var _ rpc.Handler = new(DaoHandler)

type Handler interface {
	Handle(msg *models.RpcMessage[any]) (*entity.ResEntity, error)
	Init()
}

func NewHandler(dao Dao) *DaoHandler {
	v := new(map[string]interface{})
	typ := reflect.TypeOf(v)
	return &DaoHandler{
		Dao: dao,
		typ: typ,
	}
}

type DaoHandler struct {
	Dao Dao
	typ reflect.Type
}

func (d *DaoHandler) Init() {
	d.Dao.Init()
}

func (d *DaoHandler) Handle(msg *models.RpcMessage[any]) (res *entity.ResEntity, err error) {
	res = entity.NewResEntity()
	log.Info(msg)
	d.Dao.Save(msg.Message)
	res.Code = "200"
	res.Message = "成功"
	return
}

func (d *DaoHandler) Unmarshal(data []byte, seri seri.Serialization) (any, error) {
	v := make(map[string]interface{})
	err := seri.From(data, &v)
	return v, err
}
